//
//  RecommendPhoneVC.m
//  华康通
//
//  Created by leiyu on 16/9/20.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "RecommendPhoneVC.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "FirstTableViewController.h"
#import "UMMobClick/MobClick.h"

@import ContactsUI;

@interface RecommendPhoneVC ()<ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate>
@property (strong, nonatomic) IBOutlet UITextField *topTextField;
@property (strong, nonatomic) IBOutlet UITextField *bottomTextField;
@property (strong, nonatomic) IBOutlet UIButton *txlButton;

@property (strong, nonatomic) IBOutlet UILabel *showColorLabel;
@property (strong, nonatomic) IBOutlet UIButton *nextButton;
//延迟请求后台数据的bool值
@property (nonatomic, unsafe_unretained) BOOL isSelected;

@property (nonatomic, strong) ZTVertyStatus* vertyStatus;


@end

@implementation RecommendPhoneVC


- (ZTVertyStatus*)vertyStatus
{
    if (!_vertyStatus)
    {
        _vertyStatus = [[ZTVertyStatus alloc]init];
    }
    return _vertyStatus;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"验证码 = %@",self.verificationCode);
    self.isSelected = NO;
    self.showColorLabel.layer.cornerRadius = 6.0;
    self.showColorLabel.layer.masksToBounds = YES;
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"RecommendPhoneVC"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"RecommendPhoneVC"];
}

- (void)popRootVC
{
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = @"确认返回将中断注册，确定返回吗？";
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消", @"确定", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                NSLog(@"取消操作" );
                return ;
                break;
            default:
                [self.navigationController popViewControllerAnimated:YES];
                break;
        }
    }];
    [alertView show];
}

//关闭键盘
- (IBAction)closeKeyboard:(UITextField *)sender
{
    [sender resignFirstResponder];
    [self.bottomTextField becomeFirstResponder];
}
- (IBAction)closeBottomKeyBoard:(UITextField *)sender
{
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
    //点击密码键盘上的 go时  就会后台请求
    [self nextVC:self.nextButton];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

//判断按钮背景的颜色
- (void)judeColor
{
    if (![self.bottomTextField.text isEqualToString:@""])
    {
        self.showColorLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
    }
    else
    {
        self.showColorLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:0.1];
    }
}

//系统提示框
- (void)presentAlerControllerWithMessage:(NSString*)message withTextField:(UITextField*)textField
{
    NSLog(@"%@",message);
    [self.view endEditing:YES];

    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = message;
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"取消", @"确认", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                NSLog(@"取消操作" );
                return ;
                break;
            default:
                if (textField)
                {
                    [textField becomeFirstResponder];
                }
                break;
        }
    }];
    [alertView show];
}

//上面输入框的文字发送改变
- (IBAction)textChange1:(UITextField *)sender
{
    [self judeColor];
}

//下面输入框的文字发送改变
- (IBAction)textChange2:(UITextField *)sender
{
    [self judeColor];
}

//按下改变颜色
- (IBAction)touchDown:(UIButton *)sender
{
    if (![self.bottomTextField.text isEqualToString:@""])
    {
        self.showColorLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:1.0];
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            
            self.showColorLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
        });
    }
}

//提交（与后台交互）
- (IBAction)nextVC:(UIButton *)sender
{
    //如果填写了推荐人
    if (![self.topTextField.text isEqualToString:@""] && self.topTextField)
    {
        //验证手机号码的有效性
        if ([ExamineTool verityPhoneWithString:self.topTextField.text])
        {
            NSLog(@"手机号码填写正确!");
            [self trueForPost];
        }
        else
        {
            CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
            VertyStatusView *customView  = [VertyStatusView view];
            customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_A);
            customView.otherLabel.text = @"推荐人手机号码不存在，请重新输入/不填写";
            //    customView.layer.cornerRadius = 7.0;
            //    customView.layer.masksToBounds = YES;
            [alertView setContainerView:customView];
            [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"放弃注册", @"重新输入", nil]];
            [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
                switch (buttonIndex)
                {
                    case 0:
                        //                [textField becomeFirstResponder];
                        break;
                    default:
                        [self.topTextField becomeFirstResponder];
                        break;
                }
            }];
            [alertView show];
        }
    }
    //如果没有填写推荐人
    else
    {
        [self trueForPost];
    }
}

- (void)trueForPost
{
    if (![self.bottomTextField.text isEqualToString:@""])
    {
        //非纯字母或者纯数字 高于8位
        if ([ExamineTool verityKeyWithString:self.bottomTextField.text])
        {
            if (self.isSelected)
            {
                return;
            }
            self.isSelected = YES;
            [self performSelector:@selector(timeEnough) withObject:nil afterDelay:1.2];
        }
        //纯字母或者纯数字 或者少于8位
        else
        {
//            [self presentAlerControllerWithMessage:@"密码不符合规范！请重新输入！" withTextField:self.bottomTextField];
            ShowAlertView(@"密码不符合规范！请重新输入！",self.bottomTextField);
        }
    }
}

- (void)showAlertViewWithMsg:(NSString*)msg
{
    dispatch_async(dispatch_get_main_queue(), ^{
        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
        TextStatusView *customView  = [TextStatusView view];
        customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
        customView.bottomLabel.text = msg;
        //    customView.layer.cornerRadius = 7.0;
        //    customView.layer.masksToBounds = YES;
        [alertView setContainerView:customView];
        [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", nil]];
        [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
            switch (buttonIndex)
            {
                case 0:
                    return ;
                    break;
                default:
                    return ;
                    break;
            }
        }];
        [alertView show];
    });
}
#pragma mark  //发送注册信息
- (void)postVerificationCodeWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    //注册成功一个，进去的话 把原来登录的用户信息替换掉
    NSString* registStr = [NSString stringWithFormat:@"UserLogin"];
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        
        [XHNetworking POST:url parameters:param cacheStr:registStr jsonCache:^(id jsonCache) {
            id result = [NSJSONSerialization JSONObjectWithData:jsonCache options:0 error:nil];
            NSLog(@"注册信息本地缓存信息jsonCache = %@",result);
            //先从缓存读取缓存信息;
        } success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"发送注册信息json = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"resultCode"] isEqualToString:@"0"])
                {
                    if ([json[@"responseObject"][@"registerResult"] isEqualToString:@"0"])
                    {
                        
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            
                            //注册成功
                            dispatch_async(dispatch_get_main_queue(), ^{
                                __weak RecommendPhoneVC* wself = self;
                                self.vertyStatus.status = ^(NSInteger vertyStatus,NSInteger second)
                                {
                                    NSLog(@"vertyStatus = %ld,second = %ld",(long)vertyStatus,(long)second);
                                    if (second == 1 && vertyStatus == 0)
                                    {
                                        //注册成功
                                        //                                UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                                        //                                MyTabBarController* firstVC = [storyboard instantiateViewControllerWithIdentifier:@"TABBAR"];
                                        //                                firstVC.index = 3;
                                        //                                firstVC.selectedIndex = 3;
                                        //                                [wself presentViewController:firstVC animated:YES completion:nil];
                                        [wself.navigationController popToRootViewControllerAnimated:YES];
                                    }
                                };
                                [self.vertyStatus createVertyStatusViewWithMessage:@"恭喜您注册成功\n即将跳转到首页..." withPushType:0 withReturnStatus:^(NSInteger vertyStatus, NSInteger second) {
                                    [self.topTextField resignFirstResponder];
                                    [self.bottomTextField resignFirstResponder];
                                }];
                            });
                            
                        });
                        
                        
                    }
                    else
                    {
                        [self showAlertViewWithMsg:json[@"responseObject"][@"resultMessage"]];
                    }
                }
                else
                {
                    [self showAlertViewWithMsg:@"注册失败"];
                }
            }
        } failure:^(NSError *error) {
            NSLog(@"发送注册信息error = %@",error.userInfo);
        }];
        
    } failure:^{
        //展示广告图
        NSLog(@"检测到设备无网络连接！！！");
    }];
    
    
}



- (void)timeEnough
{
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
    if (self.topTextField.text == nil)
    {
        self.topTextField.text = @"";
    }
    if (self.bottomTextField.text == nil)
    {
        self.bottomTextField.text = @"";
    }
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"register",
                           @"requestObject":@{@"password":self.bottomTextField.text,
                                              @"mobile":self.mobile ,
                                              @"verificationCode":self.verificationCode,
                                              @"recommendCode":self.topTextField.text
                                              }
                           };
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self postVerificationCodeWithURL:url withParam:json];
    self.isSelected = NO;
}

//调用通讯录选择电话号码
- (IBAction)goPhoneList:(id)sender
{
//    ABPeoplePickerNavigationController * vc = [[ABPeoplePickerNavigationController alloc] init];
//    vc.peoplePickerDelegate = self;
//    [self presentViewController:vc animated:YES completion:nil];
    
    CNContactPickerViewController *contactPickerVC = [[CNContactPickerViewController alloc] init];
    contactPickerVC.delegate = self;//控制器实现CNContactPickerDelegate
    [self presentViewController:contactPickerVC animated:YES completion:nil];
}



//取消
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//不实现此方法，默认进入详细列表界面
/**点击联系人**/
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
// NSLog(@"%@",contact.phoneNumbers[0]);
//
//}
/**点击联系人某个属性**/
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty
{
    if ([contactProperty.value isKindOfClass:[CNPhoneNumber class]])
    {
        CNPhoneNumber *phoneNum = contactProperty.value;
        NSLog(@"%@",phoneNum.stringValue);
        NSString* newP  = phoneNum.stringValue;
        // 去除+86
        if ([newP containsString:@"+86"])
        {
            newP = [phoneNum.stringValue stringByReplacingOccurrencesOfString:@"+86" withString:@""];
        }
        //去掉横线
        if ([newP containsString:@"-"])
        {
            newP = [phoneNum.stringValue stringByReplacingOccurrencesOfString:@"-" withString:@""];
        }
        // 去除+
        if ([newP containsString:@"+"]) {
            newP = [newP stringByReplacingOccurrencesOfString:@"+" withString:@""];
        }
        
        self.topTextField.text = newP;
    }else
    {
        NSLog(@"选择的不是手机号");
    }
    
}






//
//#pragma mark -- ABPeoplePickerNavigationControllerDelegate
//
//- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
//{
//    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
//    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
//    //电话号码
//    CFStringRef telValue = ABMultiValueCopyValueAtIndex(valuesRef,index);
//    //读取firstname
//    
//    //获取个人名字（可以通过以下两个方法获取名字，第一种是姓、名；第二种是通过全名）。
//    
//    //第一中方法
//    
//    //    CFTypeRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
//    
//    //    CFTypeRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
//    
//    //    //姓
//    
//    //    NSString * nameString = (__bridge NSString *)firstName;
//    
//    //    //名
//    
//    //    NSString * lastString = (__bridge NSString *)lastName;
//    
//    //第二种方法：全名
//    
//    CFStringRef anFullName = ABRecordCopyCompositeName(person);
//    [self dismissViewControllerAnimated:YES completion:^{
//        
//        self.topTextField.text = (__bridge NSString *)telValue;
//        
//        //        self.nameLabel.text = [NSString stringWithFormat:@"%@%@",nameString,lastString];
//        
////        self.nameLabel.text = [NSString stringWithFormat:@"%@",anFullName];
//        
//        
//    }];
//    
//}


@end
